#include "includes.h"


#ifdef USE_ADC
union16_t AdcVal[8];
uint8_t AdcCh=0;
uint8_t AdcChBit=BIT0;
bit AdcFlag=0;

void AdcVrefInit(void)
{
	CMPCON1 |= BIT3;										//Vref12
	TKADCF |= BIT2;											//Vref=1.8V
	DelayMs(10);
}

void AdcInit(uint8_t ch)							//Single channel continuous convert
{
	uint8_t tmp;
	
	tmp = IE0;
	EA = 0;
#ifdef USE_TK_ADC_ISR
	IE1 &= ~BIT5;
#endif	//USE_TK_ADC_ISR
	TKCON1 &= ~BIT7;										//Stop ADC
	TKCON0 &= ~BIT6;										//Disable ADC
	ASW1 = ch;
	TKCHS1 = ch;
	TKCON1 |= BIT6|BIT4;								//32 times
	TKCON0 |= BIT6|BIT2|BIT1;						//Enable ADC|1/8sysclk
	DelayUs(5);
////////////////////////////////////////
	TKCON1 |= BIT7;											//Start ADC
	TKADCF |= BIT3;											//Start ADC continuously convert
////////////////////////////////////////
#ifdef USE_TK_ADC_ISR
	IE1 |= BIT5;
#endif	//USE_TK_ADC_ISR
	IE0 = tmp;
}

#ifdef USE_ADC_DEMO
void AdcDemo(void)
{
	if(AdcFlag)
	{
		AdcFlag = 0;
		LED0 = ~LED0;
//	AdcVal[AdcCh].u8[0] = TKDATH;
//	AdcVal[AdcCh].u8[1] = TKDATL;
		UartTxDat(0xA5);
		UartTxDat(AdcCh);
		UartTxDat(AdcVal[AdcCh].u8[0]);
		UartTxDat(AdcVal[AdcCh].u8[1]);
		UartTxDat(0xAA);
		AdcCh++;
		AdcChBit <<= 1;
		if(AdcCh>7)
		{
			AdcCh = 0;
			AdcChBit = BIT0;
		}
		AdcInit(AdcChBit);
	}
}
#endif	//USE_ADC_DEMO
#endif	//USE_ADC


#ifdef USE_TMP_SEN
void TmpScan(void)
{
	IE1 &= ~BIT5;												// Disable ADC interrupt
	TKCON1 |= BIT6|BIT4;								// 32 times
	TKCON0 |= BIT5|BIT2|BIT1;						// Temp_en| 1/8sysclk
	DelayUs(5);
	TKCON1 |= BIT7;											// Start ADC
	while((TKCON1&BIT7)==0);
	IRCON &= ~BIT5;											// Clear ADC interrupt flag
}

#ifdef USE_TMP_SEN_DEMO
void TmpSenDemo(void)
{
	TmpScan();
	LED0=~LED0;
	UartTxDat(0xA5);
	UartTxDat(0);
	UartTxDat(TKDATH);
	UartTxDat(TKDATL);
	UartTxDat(0xAA);
}
#endif	//USE_TMP_SEN_DEMO
#endif	//USE_TMP_SEN



